package br.com.async.infrastructure;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import br.com.async.domain.AgileRoomEntity;

public abstract class AbstractRepositoryImpl<T extends AgileRoomEntity<Integer>, E extends Serializable>
		extends HibernateDaoSupport implements AbstractRepository<T, E> {
	protected Class<T> entityClass;

	public AbstractRepositoryImpl(Class<T> ec) {
		this.entityClass = ec;
	}

	@Override
	public void disable(T entity) {
		getHibernateTemplate().delete(entity);
	}

	@Override
	public T findByCode(E code) {
		return getHibernateTemplate().get(entityClass, code);
	}

	@Override
	public List<T> list() {

		Criteria criteria = getSession().createCriteria(entityClass);
		criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		return criteria.list();
	}

	protected List<E> getCodes(Integer index) {
		Criteria criteria = getSession().createCriteria(entityClass);
		criteria.setProjection(Projections.distinct(Projections
				.property("code")));
		criteria.setFirstResult(index);
		criteria.setMaxResults(20);
		criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		return criteria.list();
	}

	@Override
	public void persist(T entity) {
		getHibernateTemplate().save(entity);

	}

	@Override
	public void update(T entity) {
		getHibernateTemplate().merge(entity);

	}

}